import msg from "../../../utils/msg";
import { shuffleArray } from "../../../utils/util";
import { expComList, exportDraw,exportDraw2, getDraw, getScore, joiner_list, saveDraw, writeScore } from "../../../utils/request/api";
import User from "../../../utils/user";
import { filePath1 } from "../../../utils/request/route";
import Notify from "../../../miniprogram_npm/@vant/weapp/notify/notify";
// pages/compete/player/player.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //1.头像 2.昵称 3.报名时间 4.联系方式
    playerList: [
      {team_logo: "", team_name: "", add_time: "", sign_game_contect: "", score: '', team_id: '',
      member:[
        {sign_gfid:0,sign_name:'',score:''},
      ] 
    },
    ],
    filePath1,
    //抽签列表 属性同上
    drawList: [],
    drawType:'1',//分组抽签方式
    showDraw: false,//显示抽签
    hasDrawResult: false,//已有抽签结果
    //抽签输入列表
    input: {
      //分组
      group: 1 as number,
      number: 1 as number,
      //随机
      start: 1 as number,
      end: 1 as number,
    },
    //分组抽签-所有号码
    allNumber: {} as { [key: number]: boolean },
    showNumber: false,//
    drawList2: {} as { [key: number]: { number: (number|string)[], detail: any } },//随机抽签列表
    active: 0,//tab标识
    is_organizer: false,//是否为赛事组织者-是否有管理赛事的权利
    //所需赛事信息
    com: {
      title: '' as string,
      count: 1 as number,
      game_id: 0 as number,
      game_data_id: 0 as number,
    },
    //抽签选择
    drawTools: [
      {
        name: '随机排号',
        subname: '一人一号，随机分配',
        id: 1,
      },
      {
        name: '分组抽签',
        subname: '将选手分成若干组',
        id: 2,
      },
    ],
    randomAllocation: false,//随机分配
    //登记赛事所需数据
    score:{
      team_id:'' as string,
      GF_ID:0 as number,
      name:'' as string,
      score:'' as string,
    },
    showScore:false,
  },
  async setDraw() {
    await msg.confirm('设置后抽签结果对所有选手可见', '重复设置会覆盖上一次抽签');
    msg.Loading();
    let com = this.data.com;
    let user = new User;
    //设置抽签结果
    let list:any = this.data.drawList;
    if(this.data.drawType=='2') list = this.data.drawList2;
    let res = await saveDraw({ game_id: com.game_id, game_data_id: com.game_data_id, data: JSON.stringify(list), GF_ID: user.GF_ID, type: parseInt(this.data.drawType) }).then((res: any) => { return res; });
    msg.hideLoading();
    if (res.data.code != '200') { msg.show('网络错误', '请稍后再试'); return; }
    msg.show('发布成功', '');
  },
  onChange(e: any) {
    let number = e.currentTarget.dataset.number;
    let allNumber = this.data.allNumber;
    allNumber[number] = e.detail;
    this.setData({
      allNumber: allNumber,
    });
  },
  onChange2(e: any) {
    this.setData({
      drawType: e.detail,
    });
  },
  writeScore:async function(){
    let score = this.data.score;
    let com = this.data.com;
    let playerList = this.data.playerList;
    playerList.forEach((player,index)=>{
      if(player.team_id==score.team_id) playerList[index].score=score.score;
    });
    this.setData({
      playerList,
    });
    let res =await writeScore({game_id: com.game_id, game_data_id: com.game_data_id,score:score.score,team_id:score.team_id});
    Notify({ type: "success", message: '登记成功'  });
    this.setData({
      showScore:false,
    });
  },
  score(e:any){
    let dataset = e.currentTarget.dataset;
    let player = this.data.playerList[dataset.index];
    this.setData({
      ['score.team_id']:player.team_id,
      ['score.name']:player.team_name,
      //['score.GF_ID']:dataset.GF_ID,
      showScore:true,
    });
  },
  //导出选手列表
  async export() {
    let com = this.data.com;
    // if (!(com.count > 0)) {
    //   msg.show('暂无选手报名', '无法导出名单'); return;
    // }
    msg.Loading();
    await expComList(JSON.stringify(this.data.playerList), JSON.stringify(com), '选手名单');
    msg.hideLoading();
  },
  async exportDraw(){
    let com = this.data.com;
    msg.Loading();
    if(this.data.drawType=='1')
      await exportDraw(JSON.stringify(this.data.drawList), JSON.stringify(com), '抽签结果');
    else 
      await exportDraw2(JSON.stringify(this.data.drawList2), JSON.stringify(com), '抽签结果');
    msg.hideLoading();
  },
  drawLots(groups: number, perGroup: number, list: any[]): any[] {
    // const totalLots = groups * perGroup;
    // 检查抽签列表长度是否符合要求
    // if (list.length !== totalLots) {
    //   console.error("抽签列表长度与分组数及每组抽签数不匹配");
    //   return null;
    // }
    // 洗牌，打乱抽签列表的顺序
    const shuffledList = [...list].sort(() => Math.random() - 0.5);
    // 分组抽签
    const result: any[] = [];
    for (let i = 0; i < groups; i++) {
      const group: any[] = [];
      for (let j = 0; j < perGroup; j++) {
        if((i * perGroup + j)>=shuffledList.length) continue;
        group.push(shuffledList[i * perGroup + j]);
      }
      result.push(group);
    }
    return result;
  },
  //抽签
  draw() {
    let input = this.data.input;
    let length = this.data.playerList.length;
    if(length==0){
      msg.show('没有选手时不能抽签', ''); return;
    }
    // if (length < input.group) {
    //   msg.show('报名人数不足', '报名人数只有' + length + '人,不足以分成' + input.group + '组'); return;
    // }
    // if (length < input.group * input.number) {
    //   msg.show('报名人数不足', '报名人数只有' + length + '人,本次抽签需要' + input.group + '×' + input.number + '=' + input.group * input.number + '人'); return;
    // }
    //进入抽签
    msg.Loading();
    if(this.data.drawType=='1'){
      if (!(input.group > 0)) {
        msg.show('参数有误', '分组数必须为阿拉伯数字且大于0'); return;
      }
      input.number = Math.ceil(length/(input.group));
    }
    else{
      if (!(input.number > 0)) {
        msg.show('参数有误', '每组人数必须为阿拉伯数字且大于0'); return;
      }
      input.group = Math.ceil(length/(input.number));
    }
    let res: any = this.drawLots(input.group, input.number, this.data.playerList);
    this.setData({
      drawList: res,
      hasDrawResult: true,
      hasDrawResult2: false,
      active: 1,
      drawType:'1',
    })
    this.onClose();
    msg.hideLoading();
  },
  draw2() {
    let numbers =[] as string[];
    let allNumber = this.data.allNumber;
    for (let key in allNumber) numbers.push(key);
    if (numbers.length == 0) {
      msg.show('请选择至少一个号码');
      return;
    }
    //打乱选手顺序
    let playerList = this.data.playerList;
    if(playerList.length==0){
      msg.show('没有选手时不能抽签', ''); return;
    }
    playerList = shuffleArray(playerList);
    numbers=shuffleArray(numbers);
    let drawList2 = {} as { [key: number]: { number: (number|string)[], detail: any } };
    playerList.forEach((item,index)=>{
      drawList2[item.member[0].sign_gfid] = { number: [parseInt(numbers[index])||'轮空'], detail: { name: item.team_name, phone: item.sign_game_contect,logo: item.team_logo},};
    });
    if(playerList.length<numbers.length){
      let temp =[] as number[];
      for(let i=playerList.length;i<numbers.length;i++) temp.push(parseInt(numbers[i]));
      temp.sort();
      drawList2[999999]={ number: temp, detail: { name: '轮空号码'}};
      //排列
    }
    // for (let key in allNumber) {
    //   if (!allNumber[key]) continue;//跳过该号码
    //   //if (index >= playerList.length) index = 0;//新一轮
    //   if (index >= playerList.length){//有轮空的情况
    //   }
    //   let player = playerList[index];
    //   if (!drawList2[player.member[0].sign_gfid]) {
    //     drawList2[player.member[0].sign_gfid] = { number: [parseInt(key)], detail: { name: player.team_name, phone: player.sign_game_contect,logo: player.team_logo},};
    //   }
    //   else drawList2[player.member[0].sign_gfid].number.push(parseInt(key));
    //   index++;
    // }
    this.setData({
      drawList2,
      hasDrawResult2: true,
      hasDrawResult: false,
      active: 1,
      drawType:'2',
    });
    this.onClose();
  },
  _objKeySort(arys:any) { 
 	 //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获	取的属性名进行排序，newkey是一个数组
     var newkey:any = Object.keys(arys).sort();　　 
     //console.log('newkey='+newkey);
     var newObj:any = {}; //创建一个新的对象，用于存放排好序的键值对
     for(var i = 0; i < newkey.length; i++) {//遍历newkey数组
         newObj[newkey[i]] = arys[newkey[i]];  //向新创建的对象中按照排好的顺序依次增加键值对   
     }
     return newObj; //返回排好序的新对象
 },
 getScore(e: any) {
  this.setData({
    ['score.score']: e.detail.value,
  });
},
  getInput(e: any) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      ['input.' + name]: e.detail.value,
    });
    if (name == 'start' || name == 'end') this.getAllNumber();
  },
  getAllNumber() {
    console.log('getAllNumber');
    let start:number = Number(this.data.input.start);
    let end:number = Number(this.data.input.end);
    let temp = {} as { [key: number]: boolean };
    //console.log('start =',start,'end =',end);
    if (start <= 0 || (end - start)<=0 ||!start ||!end) {
      //console.log(start+'<= 0 :',start <= 0,end+' <= '+start+' :',end <= start);
      this.setData({
        allNumber: temp,
        showNumber: false,
      });
      return;
    }
    for (let i = start; i <= end; i++){ 
      console.log('i=', i);
      temp[i] = true;
    }
    //console.log('temp=', temp);
    this.setData({
      allNumber: temp,
      showNumber: true,
    });
  },
  async onSelect(e: any) {
    let id = e.detail.id;
    switch (id) {
      case 1://随机排号
        this.setData({
          randomAllocation: true,
        });
        break;
      case 2://分组
        this.showDraw();
        break;
      case 3:

        break;
      case 4:

        break;
    }
  },
  showTools() {
    //showTools
    this.setData({
      showTools: true,
    });
  },
  showDraw() {
    this.setData({
      showDraw: true,
    });
  },
  closeTools() {
    this.setData({
      showTools: false,
    });
  },
  onClose() {
    this.setData({
      showDraw: false,
      showTools: false,
      randomAllocation: false,
      showScore:false,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options: any) {
    let com = JSON.parse(options.com);
    let user = new User;
    this.setData({
      com: com,
      is_organizer: (com.game_club_id == user.club_id),
    })
    if (options.showDraw) {
      this.setData({
        showTools: true,
      });
    }
    //报名列表
    msg.Loading('获取报名列表');
    await joiner_list({game_id:this.data.com.game_id,game_data_id:this.data.com.game_data_id})
    .then((res:any)=>{
      this.setData({
        playerList:res.data.datas,
      });
      msg.hideLoading();
    });
    //抽签
    msg.Loading('获取抽签列表');
    let res = await getDraw({ game_id: com.game_id, game_data_id: com.game_data_id }).then((res: any) => { return res.data.data; });
    if (res.list) {
      let list = JSON.parse(res.list);
      switch (res.type) {
        case "1":
          this.setData({
            hasDrawResult: true,
            drawList: list,
            drawType:"1",
          }); break;
        case "2":
          this.setData({
            hasDrawResult2: true,
            drawList2: list,
            drawType:"2",
          }); break;
      }
    }
    //成绩
    msg.Loading('获取成绩中');
    await getScore({game_id:this.data.com.game_id,game_data_id:this.data.com.game_data_id})
    .then((res:any)=>{
      let playerList = this.data.playerList;
      let score = res.data.data;
      console.log('score=',score);
      playerList.forEach((player,index)=>{
        score.forEach((item:any) => {
          if(player.team_id==item.team_id){
            // player.member.forEach((member:any,index2)=>{
            //   playerList[index].member[index2]['score']=score['score'];
            // })
            //console.log('player=',playerList[index],'score=',item['score']);
            //console.log('player=',playerList[index],'score=',item['score']);
            playerList[index].score=item['score'];
          }
        });
      });
      this.setData({
        playerList,
      })
      msg.hideLoading();
    });
    msg.hideLoading();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})